<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Validator,Auth,Redirect,App\Http\Requests\AuthRequest;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'getLogout']);
    }

	protected $redirectPath = '/';

	protected $loginPath = 'auth/login';


    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }

    /**
     * 登录
     * @return [type] [description]
     */
	public function getLogin()
	{
		return view('auth.login');
	}
    /**
     * 登陆处理方法
     */
    public function postLogin(AuthRequest $request)
    {
        if (Auth::attempt(['email' => $request->email, 'password' => $request->password],isset($request->remember) )) {

            return redirect('/');
        }
        
        Auth::logout();
        
        return back()->withInput()->with('errorInfo','Email或密码错误');

    }
    /**
     * 登出
     * @return [type] [description]
     */
    public function getLogout()
    {
        Auth::logout();
        return redirect('auth/login');
    }

    /**
     * 注册
     * @return [type] [description]
     */
    public function getRegister()
    {
        return view('auth.register');
    }

    /**
     * 用户注册处理
     * @param  AuthRequest $request [description]
     * @return [type]               [description]
     */
    public function postRegister(AuthRequest $request)
    {
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password)
        ]);

        $user->roles()->attach(1);  //注册后成为普通用户
        
        Auth::login($user);

        return redirect($this->redirectPath)->with('message','注册成功');
    }
}
